# -*- coding:UTF-8 -*- #

from multiprocessing import Process,Lock
import time
import json

def show(i):
    with open('/var/www/html/python/app/ticket.txt') as f:
        dic = json.load(f)
    print('余票: %s' % dic)

def buy_ticket(i,lock):
    lock.acquire()
    with open('/var/www/html/python/app/ticket.txt') as f:
        dic = int(json.load(f))
        time.sleep(0.1)
    if  dic > 0 :
        dic -=1
        print('\033[32m%s买到票了\033[0m'%i) #console改为绿色
    else:
        print('\033[31m%s没有买到票了\033[0m'%i) #console改为红色
    time.sleep(0.1)
    with open('/var/www/html/python/app/ticket.txt', 'w') as f:
        json.dump(str(dic), f) #修改json文件,减去被买去的票
    lock.release() #释放钥匙

if __name__ == "__main__":
    for i in range(10):
        p = Process(target=show, args=(i,))
        p.start()

    lock = Lock()
    for i in range(10):
        p = Process(target=buy_ticket, args=(i, lock))
        p.start()
